<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>季度计划管理</title>
<meta name="decorator" content="default" />
<link href="${ctxStatic}/bootstrap-editable/css/bootstrap-editable.css" rel="stylesheet" />
<link href="${ctxStatic}/bootstrap-table/bootstrap-table.min.css" rel="stylesheet" />
<script src="${ctxStatic}/bootstrap-editable/js/bootstrap-editable.js"></script>
<script src="${ctxStatic}/bootstrap-table/bootstrap-table.js"></script>
<script src="${ctxStatic}/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
<script src="${ctxStatic}/bootstrap-table/extensions/editable/bootstrap-table-editable.js"></script>
<script src="${ctxStatic}/common/format/formatOrderData.js"></script>
<style type="text/css">
	input[type="checkbox"] {
		display: block;
	}
</style>
<script type="text/javascript">
$(document).ready(function() {
	$("#inputForm").validate({
		submitHandler: function(form) {
			postOrderDetil(form);
		},
		errorContainer: "#messageBox",
		errorPlacement: function(error, element) {
			$("#messageBox").text("输入有误，请先更正。");
			if (element.is(":checkbox") || element.is(":radio") || element.parent().is(".input-append")) {
				error.appendTo(element.parent().parent());
			} else {
				error.insertAfter(element);
			}
		}
	});

	$('#tab').bootstrapTable({
		toolbar: "#toolbar",
		clickToSelect: true,
		uniqueId: "vid",
		columns: [{
	        field:"选择",
	        checkbox: true
	    },{
			field: 'id',
			title: 'id',
			visible: false
		},{
			field: 'vid',
			title: 'vid',
			visible: false
		},{
			field: 'vaccineid',
			title: '疫苗编码'
		},{
			field: 'vaccname',
			title: '疫苗名称'
		},{
			field: 'companyName',
			title: '生产企业'
		},{
			field: 'type',
			title: '类型',
            width : '100px',
            editable: {
                type: 'select2',
                mode:'inline',
                inputclass:'input-mini',
                source: function (a,b,c,d) {
                    var list = JSON.parse('${fns:getDictListJson("bs_vaccine_type")}');
                    var result = [];
                    for (var i in list) {
                    	result.push({
                    		text : list[i].label,
                    		value : list[i].value
                    	});
                    }
                    return result;
                }
            }
		},{
			field: 'spec',
			title: '规格',
			width: '100px',
			editable: {
				type: 'text',
				emptytext: '0',
				mode: 'inline',
				inputclass: 'input-mini',
				validate: function(v) {
					var reg = /^\d+(\.\d+)?$/;
					if (!reg.test(v)) {
						return '输入不合法';
					}
				}
			}
		},{
			field: 'dose',
			title: '剂量',
            width : '150px',
            editable: {
                type: 'select2',
                mode:'inline',
                inputclass:'input-mini',
                source: function (a,b,c,d) {
                    var list = JSON.parse(${fns:toJson(bsVaccineInfoList)});
                    var result = [];
                    for (var i in list) {
                    	result.push({
                    		text : list[i].dose,
                    		value : list[i].dose
                    	});
                    }
                    return result;
                }
            }
		},{
			field: 'doseType',
			title: '剂型',
            width : '100px',
            editable: {
                type: 'select2',
                mode:'inline',
                inputclass:'input-mini',
                source: function (a,b,c,d) {
                    var list = JSON.parse('${fns:getDictListJson("bs_vaccineInfo_doseType")}');
                    var result = [];
                    for (var i in list) {
                    	result.push({
                    		text : list[i].label,
                    		value : list[i].value
                    	});
                    }
                    return result;
                }
            }
		},{
			field: 'containerType',
			title: '容器类型',
            width : '100px',
            editable: {
                type: 'select2',
                mode:'inline',
                inputclass:'input-mini',
                source: function (a,b,c,d) {
                    var list = JSON.parse('${fns:getDictListJson("bs_vaccineInfo_containerType")}');
                    var result = [];
                    for (var i in list) {
                    	result.push({
                    		text : list[i].label,
                    		value : list[i].value
                    	});
                    }
                    return result;
                }
            }
		},{
			field: 'sellPrice',
			title: '价格（元/支、粒）',
			width: '100px',
			editable: {
				type: 'text',
				emptytext: '0.0',
				mode: 'inline',
				inputclass: 'input-mini',
				validate: function(v,a,b,c) {
					var reg = /^\d+(\.\d+)?$/;
					if (!reg.test(v)) {
						return '价格不合法';
					}
				}
			}
		},{
			field: 'monthNum',
			title: '上报月数',
			visible: false
		},{
			field: 'planNumYear',
			title: '季度计划数',
			width: '100px',
			editable: {
				type: 'text',
				emptytext: '0',
				mode: 'inline',
				inputclass: 'input-mini',
				validate: function(v) {
					var reg = /^\d+(\.\d+)?$/;
					if (!reg.test(v)) {
						return '输入不合法';
					}
				}
			}
		},{
			field: 'planNumMonth',
			title: '月度计划数'
		},{
			field: 'planNumYearRemain',
			title: '季度累计领取数',
			visible: false
		},{
			field: 'remarks',
			title: '备注',
			width: '150px',
			editable: {
				type: 'text',
				emptytext: '--',
				mode: 'inline',
				inputclass: 'input-mini',
				validate: function(v) {
					
				}
			}
		}],
		onEditableSave: function(field, row, oldValue, $el) {
			debugger;
			if (field == 'type'){
				var rows = $('#tab').bootstrapTable('getData');
				for(var i = 0 in rows){
					if(row.vid != rows[i].vid){
						if(row.vaccineid == rows[i].vaccineid
							&& row.vaccname == rows[i].vaccname
							&& row.sellPrice == rows[i].sellPrice
							&& row.spec == rows[i].spec
							&& row.dose == rows[i].dose
							&& row.doseType == rows[i].doseType
							&& row.containerType == rows[i].containerType
							&& row.companyName == rows[i].companyName
							){
							if(row.type == rows[i].type){
								row.type = '';
								$('#tab').bootstrapTable('updateByUniqueId', { id: row.vid, 'row':row});
								layer.msg("该信息已重复存在，请重新输入");
							}
						}
					}
				}
			}
			if (field == 'spec'){
				var rows = $('#tab').bootstrapTable('getData');
				for(var i = 0 in rows){
					if(row.vid != rows[i].vid){
						if(row.vaccineid == rows[i].vaccineid
							&& row.vaccname == rows[i].vaccname
							&& row.type == rows[i].type
							&& row.sellPrice == rows[i].sellPrice
							&& row.dose == rows[i].dose
							&& row.doseType == rows[i].doseType
							&& row.containerType == rows[i].containerType
							&& row.companyName == rows[i].companyName
							){
							if(row.spec == rows[i].spec){
								row.spec = '';
								$('#tab').bootstrapTable('updateByUniqueId', { id: row.vid, 'row':row});
								layer.msg("该信息已重复存在，请重新输入");
							}
						}
					}
				}
			}
			if (field == 'dose'){
				var rows = $('#tab').bootstrapTable('getData');
				for(var i = 0 in rows){
					if(row.vid != rows[i].vid){
						if(row.vaccineid == rows[i].vaccineid
							&& row.vaccname == rows[i].vaccname
							&& row.type == rows[i].type
							&& row.spec == rows[i].spec
							&& row.sellPrice == rows[i].sellPrice
							&& row.doseType == rows[i].doseType
							&& row.containerType == rows[i].containerType
							&& row.companyName == rows[i].companyName
							){
							if(row.dose == rows[i].dose){
								row.dose = '';
								$('#tab').bootstrapTable('updateByUniqueId', { id: row.vid, 'row':row});
								layer.msg("该信息已重复存在，请重新输入");
							}
						}
					}
				}
			}
			if (field == 'doseType'){
				var rows = $('#tab').bootstrapTable('getData');
				for(var i = 0 in rows){
					if(row.vid != rows[i].vid){
						if(row.vaccineid == rows[i].vaccineid
							&& row.vaccname == rows[i].vaccname
							&& row.type == rows[i].type
							&& row.spec == rows[i].spec
							&& row.dose == rows[i].dose
							&& row.sellPrice == rows[i].sellPrice
							&& row.containerType == rows[i].containerType
							&& row.companyName == rows[i].companyName
							){
							if(row.doseType == rows[i].doseType){
								row.doseType = '';
								$('#tab').bootstrapTable('updateByUniqueId', { id: row.vid, 'row':row});
								layer.msg("该信息已重复存在，请重新输入");
							}
						}
					}
				}
			}
			if (field == 'containerType'){
				var rows = $('#tab').bootstrapTable('getData');
				for(var i = 0 in rows){
					if(row.vid != rows[i].vid){
						if(row.vaccineid == rows[i].vaccineid
							&& row.vaccname == rows[i].vaccname
							&& row.type == rows[i].type
							&& row.spec == rows[i].spec
							&& row.dose == rows[i].dose
							&& row.doseType == rows[i].doseType
							&& row.sellPrice == rows[i].sellPrice
							&& row.companyName == rows[i].companyName
							){
							if(row.containerType == rows[i].containerType){
								row.containerType = '';
								$('#tab').bootstrapTable('updateByUniqueId', { id: row.vid, 'row':row});
								layer.msg("该信息已重复存在，请重新输入");
							}
						}
					}
				}
			}
			if (field == 'sellPrice'){
				var rows = $('#tab').bootstrapTable('getData');
				for(var i = 0 in rows){
					if(row.vid != rows[i].vid){
						if(row.vaccineid == rows[i].vaccineid
							&& row.vaccname == rows[i].vaccname
							&& row.type == rows[i].type
							&& row.spec == rows[i].spec
							&& row.dose == rows[i].dose
							&& row.doseType == rows[i].doseType
							&& row.containerType == rows[i].containerType
							&& row.companyName == rows[i].companyName
							){
							if(row.sellPrice == rows[i].sellPrice){
								row.sellPrice = '';
								$('#tab').bootstrapTable('updateByUniqueId', { id: row.vid, 'row':row});
								layer.msg("该信息已重复存在，请重新输入");
							}
						}
					}
				}
			}
        	if (field == 'monthNum' || field == 'planNumYear' ){
        		row.planNumMonth = Math.ceil( row.planNumYear / row.monthNum );
        		$('#tab').bootstrapTable('updateByUniqueId', { id: row.vid, 'row':row});
        	}
			setTimeout(function() {
				$('#tab').find('[data-uniqueid="' + row.vid + '"]').next().find('[data-name="' + field + '"]').editable('show');
			},
			200);
		}
	});
	
	//切换季度
	$("#quarter").click(function(){
		titleChange();
	});

	//变换标题
	$('#planTitleStr').editable({
		validate: function(value) {
		    // TODO 校验数字是否合法
		},success: function(response, newValue) {
			// 成功后回调
			$("#planTitle").val(newValue);
		}
	});
	
	//获取疫苗基本信息
	$("#btnAddVacc").click(function() {
		var url = "${ctx}/vaccinate/bsVaccineInfo/findList?type=2";
		var height = window.screen.availHeight * 0.6;
		var width = window.screen.availWidth * 0.7;
		layer.open({
			type : 2,
			title : '疫苗基本信息',
			shadeClose : true,
			shade : 0.8,
			resize : false,
			area : [ width + "px", height + "px" ],
			content : url
		});
	});
	
	//删除选择疫苗
	$("#btnDeleteAddVacc").click(function() {
		var ids = $.map($('#tab').bootstrapTable('getSelections'), function (row) {
			return row.vid;
        });
        
		$('#tab').bootstrapTable('remove', {
            field: 'vid',
            values: ids
        });
	});
	
	//保存
	$("#btnSubmit").click(function(){
		$("#planStatus").val("0");
		$("#inputForm").submit();
	});
	
	//保存并上报
	$("#btnSubmitReport").click(function(){
		var loadIndex = layer.load(2);
		var param = {
			"fromOrgCode" : $("#fromOrgCode").val(),
			"toOrgCode" : $("#toOrgCodeId").val(),
			"planDate" : $("#planDate").val(),
			"quarter" : $("#quarter").val()
		};
		$.post("${ctx}/plan/bsPlanYearToll/checkPlanYear", param, function(result){
			layer.close(loadIndex);
			if (result.success == false){
				layer.alert(result.msg, {icon: 2});
			} else if(result.success == true){
				$("#planStatus").val("1");
				$("#inputForm").submit();
			}
		});
	});
	
});

//赋值
function addInfo(obj) {
	debugger;
	$('#tab').bootstrapTable('getData', false);
	var rows = $('#tab').bootstrapTable('getData');
	for(var i = 0 in rows){
		if(obj.vaccineId == rows[i].vaccineid
			&& obj.vaccName == rows[i].vaccname
			&& obj.type == rows[i].type
			&& obj.spec == rows[i].spec
			&& obj.dose == rows[i].dose
			&& obj.doseType == rows[i].doseType
			&& obj.containerTypeNam == rows[i].containerType
			&& obj.companyName == rows[i].companyName
			&& '' == rows[i].sellPrice
			){
			layer.msg("该信息已重复存在，请勿多次选择");
			return;
		}
	}
	var tr = {
		id : '',
		vid : guid(),
		vaccineid : obj.vaccineId,
		vaccname : obj.vaccName,
		type : '2',
		spec : obj.spec,
		dose : obj.dose,
		doseType : obj.doseType,
		containerType : obj.containerTypeNam,
		companyName : obj.companyName,
		sellPrice : '',
		monthNum : '3',
		planNumYear : '',
		planNumMonth : '',
		remarks : ''
	}
	$('#tab').bootstrapTable('append', tr);
}

//日期变更联动标题
function titleChange(){
	var date = $dp.cal.getDateStr("yyyy");
	var quarter = $("#quarter").val();
	var fromOrgName = $("#fromOrgName").val();
	var planTitleStr = date+"年第"+quarter+"季度计划-"+fromOrgName;
	$("#planTitle").val(planTitleStr);
	$('#planTitleStr').editable('setValue', planTitleStr, false);
	$('#tab').bootstrapTable('refresh');
}

//表单保存时  将此方法中的数据进行保存
function postOrderDetil(form) { 
	var rows = $('#tab').bootstrapTable('getData');
	$("#tableData").val(JSON.stringify(rows));
	layer.confirm('确定保存？', {
		icon: 3, 
		title:'提示',
		btn : [ '保存', '取消' ]
	}, function() {
		layer.load(2);
		loading('正在提交，请稍等...');
		form.submit();
	});
}
</script>
</head>
<body>
	<ul class="nav nav-tabs">
		<li class="active"><a href="${ctx}/plan/bsPlanYearToll/formAdd">季度计划填报</a></li>
	</ul>
	<form:form id="inputForm" modelAttribute="bsPlanYearToll" action="${ctx}/plan/bsPlanYearToll/save" method="post" class="breadcrumb form-search">
		<form:hidden path="id" />
		<form:hidden path="planTitle" />
		<form:hidden path="planStatus" />
		<form:hidden path="fromOrgCode" />
		<form:hidden path="type" />
		<input id="tableData" name="tableData" type="hidden">
		<sys:message content="${message}" />
		<table class="table table-bordered">
			<tr>
				<th>填报单位：</th>
				<td><input readonly type="text" name="fromOrgName" id="fromOrgName" class="input-medium" value="${bsPlanYearToll.fromOrgName}" /></td>
				<th>填报人：</th>
				<td><input type="text" name="planBy" id="planBy" class="input-medium" value="${bsPlanYearToll.planBy}" /></td>
				<th>审核单位：</th>
				<td><sys:treeselect2 id="toOrgCode" name="toOrgCode" value="${bsPlanYearToll.toOrgCode}" labelName="toOrgName"
						labelValue="${bsPlanYearToll.toOrgName}" title="部门" url="/sys/office/treeData2?areaType=3" cssClass="input-medium"
						allowClear="true" notAllowSelectParent="true" /></td>
				<th>计划日期：</th>
				<td><input name="planDate" id="planDate" type="text" readonly="readonly"
					maxlength="20" class="input-medium Wdate "
					value="<fmt:formatDate value="${bsPlanYearToll.planDate}" pattern="yyyy"/>"
					onclick="WdatePicker({dateFmt:'yyyy',isShowClear:false,onpicked: titleChange });" /></td>
				<th>计划季度：</th>
				<td>
					<form:select path="quarter" class="input-medium">
						<form:option value="1" label="第1季度"/>
						<form:option value="2" label="第2季度"/>
						<form:option value="3" label="第3季度"/>
						<form:option value="4" label="第4季度"/>
					</form:select>
				</td>
			</tr>
		</table>
		<div>
			<shiro:hasPermission name="plan:bsPlanYearToll:edit">
				<button id="btnSubmit" class="btn btn-primary" type="button">保存</button>
				<button id="btnSubmitReport" class="btn btn-primary" type="button">保存并上报</button>
			</shiro:hasPermission>
			<button id="btnCancel" class="btn" type="button" onclick="history.go(-1)">返回</button>
		</div>
	</form:form>
	<div class="control-group table">
		<fieldset>
			<legend>
		    	<span id="planTitleStr" data-mode="inline"  data-inputclass="input-xlarge" data-type="text">${bsPlanYearToll.planTitle}</span>
		    </legend>
		</fieldset>
		<div id="toolbar">
			<button id="btnAddVacc" class="btn btn-primary" type="button">选择疫苗</button>
			<button id="btnDeleteAddVacc" class="btn btn-primary" type="button">删除</button>
		</div>
		<table id="tab" class="table table-bordered table-condensed">
		</table>
	</div>
</body>
</html>